import * as vscode from "vscode";
import { loadMark, parseMark } from "./codePaser";

export class NodeItem extends vscode.TreeItem {
  children: NodeItem[] = [];
  constructor(
    label: string,
    collapsibleState?: vscode.TreeItemCollapsibleState
  ) {
    super(label, collapsibleState);
  }
}

export class SideList implements vscode.TreeDataProvider<NodeItem> {
  extensionUri;
  catalog: { [key: string]: string } | undefined;
  vulnCode: Array<string> = [];
  constructor(extensionUri: vscode.Uri) {
    this.extensionUri = extensionUri;
    const markFilePath = vscode.Uri.joinPath(
      this.extensionUri,
      "resource",
      "Mark.md"
    );
    (async () => {
      try {
        const markFile = await loadMark(markFilePath);
        const { catalog, dictionary } = parseMark(markFile);
        this.catalog = catalog;
      } catch (err) {
        console.error(err);
      }
    })();
  }

  private _onDidChangeTreeData: vscode.EventEmitter<
    NodeItem | undefined | null | void
  > = new vscode.EventEmitter<NodeItem | undefined | null | void>();
  readonly onDidChangeTreeData: vscode.Event<
    NodeItem | undefined | null | void
  > = this._onDidChangeTreeData.event;

  refresh(): void {
    let editor = vscode.window.activeTextEditor;
    if (!editor) {
      return;
    }
    this.vulnCode = [];
    let text = editor.document.getText();
    let words = text.match(/\w+/g);
    if (words && words.length > 0) {
      for (const word of words) {
        for (const regex in this.catalog) {
          if (word.match(regex)) {
            this.vulnCode.unshift(word + this.catalog[regex]);
            break;
          }
        }
      }
      console.log(this.vulnCode);
    } else {
      console.log("没有找到单词");
    }
    this._onDidChangeTreeData.fire();
  }

  getTreeItem(element: NodeItem): vscode.TreeItem | Thenable<NodeItem> {
    return element;
  }
  getChildren(element?: NodeItem): vscode.ProviderResult<NodeItem[]> {
    console.log(this.vulnCode);
    if (!element) {
      //根节点
      const treeItem = new NodeItem(
        "打开便捷代码",
        vscode.TreeItemCollapsibleState.None
      );

      treeItem.command = {
        command: "open_webview",
        title: "打开工具栏",
        arguments: [treeItem],
      };

      // 代码审计
      const vulnTree = new NodeItem(
        "代码审计",
        vscode.TreeItemCollapsibleState.Expanded
      );
      vulnTree.command = {
        command: "refresh_vuln",
        title: "重新审计",
      };

      return [treeItem, vulnTree];
    } else {
      return this.vulnCode.map((c) => {
        return new NodeItem(c, vscode.TreeItemCollapsibleState.None);
      });
    }
  }
}
